<template>
  <a-row>
    <a-card :body-style="{padding: '24px 32px'}" :bordered="false" :span="8">
      <a-col :span="5">
        <a-button @click="batchDel">
          批量删除
        </a-button>
        <a-dropdown :trigger="['click']" placement="bottomCenter" style="margin-left: 10px">
          <a-menu slot="overlay">
            <a-menu-item key="3" @click="checkALL">全部勾选</a-menu-item>
            <a-menu-item key="4" @click="cancelCheckALL">取消全选</a-menu-item>
            <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
            <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
          </a-menu>
          <a-button>
            树操作
            <a-icon type="down"/>
          </a-button>
        </a-dropdown>
        <a-alert type="info" showIcon style="margin-top: 5px">
          <div slot="message">
            <span>当前选择：{{ (checkDeptName||'') }} </span>
            <a style="margin-left: 10px;" @click="onClearSelected" v-if="checkDeptName">取消选择</a>
          </div>
        </a-alert>
        <a-input-search style="margin-bottom: 8px;margin-top: 5px" placeholder="请输入部门" @change="onChange"/>
        <template>
          <div>
            <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
              <span style="user-select: none">
                <a-tree
                  v-if="departTree.length"
                  checkable
                  checkStrictly
                  @check="onCheck"
                  @expand="onExpand"
                  @rightClick="rightHandle"
                  :defaultExpandedKeys="defaultExpandedKeys"
                  :expandedKeys="expandedKeys"
                  :autoExpandParent="autoExpandParent"
                  v-model="checkedKeys"
                  @select="onSelect"
                  :selectedKeys="selectedKeys"
                  :treeData="departTree"
                /></span>
              <a-menu slot="overlay">
                <a-menu-item @click="handleAdd" key="1" v-wx-role="50501">添加</a-menu-item>
                <a-menu-item @click="handleDelete" key="2" v-wx-role="50504">删除</a-menu-item>
                <a-menu-item @click="closeDrop" key="3">取消</a-menu-item>
              </a-menu>
            </a-dropdown>
          </div>
        </template>

      </a-col>
      <a-col :span="19">
        <a-form-model
          ref="ruleForm"
          :model="selectDeptInfo"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-model-item
            label="部门名称"
            prop="name"
            ref="name"
            :rules="$valid.required"
            :maxLength="50">
            <a-input v-model="selectDeptInfo.name" placeholder="请输入"/>
          </a-form-model-item>
          <a-form-model-item
            label="部门别名"
            prop="shorter"
            ref="shorter"
            :rules="$valid.required"
            :maxLength="50">
            <a-input v-model="selectDeptInfo.shorter" placeholder="请输入"/>
          </a-form-model-item>
          <a-form-model-item
            label="部门编码"
            prop="areaCode"
            ref="areaCode"
            :rules="$valid.required"
            :maxLength="50">
            <a-input v-model="selectDeptInfo.areaCode" placeholder="请输入"/>
          </a-form-model-item>
          <a-form-model-item label="类型">
            <a-radio-group v-model="selectDeptInfo.orgFlag" :defaultValue="0">
              <a-radion
                v-for="(item) in this.$sysDictOptions('orgFlag')"
                :key="item.k"
                @change="radioClick"
                :value="parseInt(item.k)">
                {{ item.v }}
              </a-radion>
            </a-radio-group>
          </a-form-model-item>
          <!--          <a-form-model-item-->
          <!--            v-if="selectDeptInfo.orgFlag!==0 && selectDeptInfo.orgFlag"-->
          <!--            :rules="selectDeptInfo.orgFlag!==0 && selectDeptInfo.orgFlag?$valid.required:[]"-->
          <!--            label="所在地"-->
          <!--            prop="areaCode"-->
          <!--            :maxLength="50">-->
          <!--            <wx-area-code @ok="changeAreaCode" :areaCode="selectDeptInfo.areaCode"></wx-area-code>-->
          <!--            <input type="hidden" v-model="selectDeptInfo.areaData">-->
          <!--          </a-form-model-item>-->
          <a-form-model-item
            label="上级部门"
            prop="parentId"
            :rules="$valid.required">
            <a-input v-model="selectDeptInfo.parentId" placeholder="请输入" type="hidden"/>
            <a-input-search
              placeholder="点击右侧按钮选择部门"
              v-model="selectDeptInfo.parentName"
              onfocus="this.blur()"
              @search="departCodeSearch">
              <a-button slot="enterButton" icon="search">选择</a-button>
            </a-input-search>
          </a-form-model-item>
          <a-form-model-item
            label="所在位置"
            prop="address"
            ref="address">
            <a-input v-model="selectDeptInfo.address" placeholder="请输入" :maxLength="40"/>
          </a-form-model-item>
          <a-form-model-item
            label="联系电话"
            prop="mobile"
            ref="mobile">
            <a-input v-model="selectDeptInfo.mobile" placeholder="请输入"/>
          </a-form-model-item>
          <a-form-model-item
            label="排序"
            prop="sortOrder"
            ref="sortOrder"
            :rules="$valid.numRules">
            <a-input-number :min="1" v-model="selectDeptInfo.sortOrder" placeholder="请输入"/>
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button
              type="primary"
              @click="onSubmit"
              v-if="orgCategoryDisabled&&selectDeptInfo.id!=1&&selectDeptInfo.orgFlag===0"
              v-wx-role="50502">
              修改并保存
            </a-button>
            <a-button
              type="primary"
              @click="onSubmit"
              v-if="!orgCategoryDisabled&&selectDeptInfo.orgFlag===0"
              v-wx-role="50501">
              新增
            </a-button>
            <a-button style="margin-left: 10px;" @click="resetForm" v-if="selectDeptInfo.id!=1&&selectDeptInfo.orgFlag===0">
              重置
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </a-col>
      <depart-window ref="departCodeRef" @ok="departCodeOk" :multiple-flag="false"></depart-window>
    </a-card>
  </a-row>
</template>

<script>
  import { PageView } from '@/layouts'
  import pick from 'lodash.pick'
  import { getDepartTree, getDeptInfo, departSave, departDel } from '@/api/api'
  import departWindow from '../../../components/WxDepartChoose/DepartWindow'
  import WxAreaCode from '@/components/WxAreaCode/WxAreaCode'
  import { mapActions } from 'vuex'

  let expandedKeySource = []
  let selectList = []
  let selectParentList = []
  export default {
    name: 'DepartList',
    components: {
      WxAreaCode,
      PageView,
      departWindow
    },
    data () {
      return {
        labelCol: { span: 4 },
        wrapperCol: { span: 14 },
        defaultExpandedKeys: [],
        expandedKeys: [],
        autoExpandParent: true,
        checkedKeys: [],
        selectedKeys: [],
        rightClickSelectedKey: '',
        rightClickSelectedValue: '',
        rightClickSelectedName: '',
        allTreeKeys: [],
        dropTrigger: '11',
        orgCategoryDisabled: false,
        selectDeptInfo: {
          parentId: undefined,
          parentName: undefined,
          areaCode: undefined,
          areaData: undefined,
          address: undefined,
          orgFlag: 0
        },
        checkDeptName: '',
        departTree: [],
        departListSys: []
      }
    },
    created () {
      this.initData(true)
    },
    mounted () {
    },
    watch: {
      selectedKeys (val) {
        this.$refs.ruleForm.resetFields()
      }
    },
    methods: {
      ...mapActions(['GetDeparts']),
      onSubmit () {
        this.$refs.ruleForm.validate(valid => {
          console.log(valid)
          if (valid) {
            departSave(this.selectDeptInfo).then(res => {
              this.checkDeptName = this.selectDeptInfo.name
              this.$message.success(res.content)
              this.initData(false)
              this.GetDeparts({})
            })
          } else {
            return false
          }
        })
      },
      // 获取用户对应部门弹出框提交给返回的数据
      departCodeOk (formData) {
        const departCodeNames = []
        const departCodeKeys = []
        let departCodeNameString = ''
        for (let i = 0; i < formData.departIdList.length; i++) {
          departCodeKeys.push(formData.departIdList[i].key)
          departCodeNames.push(formData.departIdList[i].title)
          departCodeNameString = departCodeNames.join(',')
        }
        if (departCodeKeys.length > 0) {
          this.selectDeptInfo.parentId = departCodeKeys[0]
          this.selectDeptInfo.parentName = departCodeNameString
        }
      },
      // 搜索用户对应的归属部门API
      departCodeSearch () {
        this.$refs.departCodeRef.add([this.selectDeptInfo.parentId])
      },
      // 重置表单
      resetForm () {
        this.selectDeptInfo.parentId = undefined
        this.selectDeptInfo.parentName = ''
        this.orgCategoryDisabled = false
        this.selectDeptInfo.id = undefined
        this.selectDeptInfo.areaCode = undefined
        this.selectDeptInfo.areaData = undefined
        this.checkDeptName = ''
        this.selectedKeys = []
        this.selectDeptInfo.address = ''
        this.$refs.ruleForm.resetFields()
      },
      // 批量删除
      batchDel: function () {
        if (!this.checkedKeys.checked || this.checkedKeys.checked.length <= 0) {
          this.$message.warning('请勾选一条记录！')
        } else {
          var ids = ''
          for (var a = 0; a < this.checkedKeys.checked.length; a++) {
            ids += this.checkedKeys.checked[a] + ','
          }
          var that = this
          this.$confirm({
            title: '确认删除',
            content: '确定要删除所选中的 ' + that.checkedKeys.checked.length + ' 条数据，以及子节点数据吗?',
            onOk: function () {
              departDel({ ids: ids }).then((res) => {
                that.$message.success(res.content)
                that.initData(false)
                that.resetForm()
              })
            }
          })
        }
      },
      handleIconChange (icon) {
        console.log('change Icon', icon)
      },
      // tree 展开
      onExpand (expandedK, expandedExtr) {
        this.expandedKeys = expandedK
      },
      // 清空选择
      onClearSelected () {
        this.resetForm()
      },
      // 触发onSelect事件时,为部门树右侧的form表单赋值
      setValuesToForm (record) {
        this.orgCategoryDisabled = true
        getDeptInfo({ departCode: record.key }).then(res => {
          const data = res.result.data
          console.log(data.areaCode)
          if (data.areaCode === undefined) {
            data.areaCode = undefined
          }
          this.selectDeptInfo = (pick(data, 'name', 'shorter', 'id', 'contact', 'sortOrder', 'parentId', 'mobile', 'parentName', 'orgFlag', 'areaCode', 'areaData', 'address'))
        })
      },
      // 触发选中事件 勾选复选框
      onCheck (checkedKeys, info) {
        console.log('onCheck', checkedKeys, info)
        this.hiding = false
        // this.checkedKeys = checkedKeys.checked
        if (this.checkStrictly) {
          this.checkedKeys = checkedKeys.checked
        } else {
          this.checkedKeys = checkedKeys
        }
      },
      // 触发点击事件
      onSelect (selectedKeys, info) {
        this.$refs.ruleForm.resetFields()
        this.selectedKeys = selectedKeys
        const record = info.node.dataRef
        this.setValuesToForm(record)
        this.checkDeptName = record.title
      },
      // 编辑情况下，禁止选择当前节点及其子节点
      diGuiTreeEdit (item, vals) {
        const data = item
        const treeAry = []
        for (const i in data) {
          const v = data[i]
          const node = {}
          if (v === null || v === undefined) {
          } else {
            if (v.children && v.children.length > 0) {
              if (v.title.indexOf(vals) > -1) {
                node.class = 'k-tree-select'
                selectList.push(v.parentId)
              } else {
                node.class = ''
              }
              node.key = v.key
              node.title = v.title
              node.parentId = v.parentId
              node.children = this.diGuiTreeEdit(v.children, vals)
              treeAry.push(node)
            } else {
              if (v.title.indexOf(vals) > -1) {
                node.class = 'k-tree-select'
                selectList.push(v.parentId)
              } else {
                node.class = ''
              }
              node.key = v.key
              node.title = v.title
              node.parentId = v.parentId
              treeAry.push(node)
            }
          }
        }
        return treeAry
      },
      // 获取父节点
      getParents (checkKey) {
        for (var i = 0; i < this.departListSys.length; i++) {
          const tmp = this.departListSys[i]
          if (tmp.id === parseInt(checkKey)) {
            selectParentList.push(tmp.key)
            if (this.checkHasParent(tmp.parentId)) {
              this.getParents(tmp.parentId)
            }
          }
        }
      },
      // 检查是否有父节点
      checkHasParent (checkKey) {
        for (var i = 0; i < this.departListSys.length; i++) {
          const tmp = this.departListSys[i]
          if (tmp.id === checkKey) {
            return tmp.id
          }
        }
      },
      // 左侧检索
      onChange (e) {
        let value = e.target.value
        if (!value) {
          value = '@@@@'
        }
        selectList = []
        selectParentList = []
        this.departTree = this.diGuiTreeEdit(this.departTree, value)
        this.expandedKeys = []
        selectList.map(x => {
          this.getParents(x)
          selectParentList.map(x => {
            this.expandedKeys.push(x)
          })
        })
        if (this.expandedKeys.length === 0) {
          this.expandedKeys = expandedKeySource
        }
      },
      // 初始化数据 参数true为第一次，
      initData (firstFlag) {
        getDepartTree().then(res => {
          if (firstFlag) {
            const treeLv2 = res.result.data[0].children.map((item, index, arr) => {
              const treeLv2Tmp = (item.key)
              return treeLv2Tmp
            })
            this.expandedKeys = treeLv2
            expandedKeySource = treeLv2
          }
          this.departTree = res.result.data
          this.getAllKeys(this.departTree)
        })
      },
      // 获取所有的key
      getAllKeys (node) {
        node.map((item, index, arr) => {
          this.allTreeKeys.push(item.key)
          const node = {}
          node.id = item.id
          node.key = item.key
          node.title = item.title
          node.parentId = item.parentId
          this.departListSys.push(node)
          if (item.children && item.children.length > 0) {
            this.getAllKeys(item.children)
          }
        })
      },
      // 右键点击下拉框改变事件
      dropStatus (visible) {
        if (visible === false) {
          this.dropTrigger = ''
        }
      },
      // 展开所有
      expandAll () {
        this.expandedKeys = this.allTreeKeys
      },
      // 关闭所有
      closeAll () {
        this.expandedKeys = []
      },
      // 全选
      checkALL () {
        this.checkedKeys = this.allTreeKeys
      },
      // 取消全选
      cancelCheckALL () {
        this.checkedKeys = []
      },
      // 添加
      handleAdd () {
        this.selectDeptInfo.parentId = undefined
        this.selectDeptInfo.parentName = ''
        this.orgCategoryDisabled = false
        this.selectDeptInfo.id = undefined
        this.checkDeptName = ''
        this.$refs.ruleForm.resetFields()

        this.selectDeptInfo.parentId = this.rightClickSelectedKey
        this.selectDeptInfo.parentName = this.rightClickSelectedName
        this.selectDeptInfo.address = ''
      },
      // 删除
      handleDelete () {
        departDel({ ids: this.rightClickSelectedKey }).then((resp) => {
          this.$message.success('删除成功!')
          this.initData(false)
        })
      },
      // 右键店家下拉关闭下拉框
      closeDrop () {
        this.dropTrigger = ''
      },
      // 右键操作方法
      rightHandle (node) {
        this.dropTrigger = 'contextmenu'
        this.rightClickSelectedKey = node.node.eventKey
        this.rightClickSelectedValue = node.node.value
        this.rightClickSelectedName = node.node.title
      },
      // 选择省市区
      changeAreaCode (data) {
        this.selectDeptInfo.areaCode = data.code
        this.selectDeptInfo.areaData = data.name
      },
      radioClick () {
        this.selectDeptInfo.areaCode = undefined
        this.selectDeptInfo.areaData = undefined
      }
    }
  }
</script>
<style scoped>
  .drawer-bootom-button {
    /*position: absolute;*/
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: left;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }
</style>
